package com.juku2024.juku.base

import android.app.Application
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.util.Log
import android.webkit.WebView
import coil.ImageLoader
import coil.executeBlocking
import coil.request.ImageRequest
import com.chad.library.adapter.base.module.LoadMoreModuleConfig
import com.cicada.player.utils.Logger
import com.rabbit.videoplayer.MixPlayerView
import com.rabbit.videoplayer.response.PlayerType
import com.wanban.adutils.AdUtils
import com.juku2024.juku.BuildConfig
import com.juku2024.juku.model.DownloadInitEventNew
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.LogC
import com.juku2024.juku.tools.RxUtils
import com.juku2024.juku.widget.LoadMoreView
import com.wanban.download.WBDownloadUtils
import com.wanban.download.listener.OnLoadCoverImageListener
import com.wanban.screencast.ScreenCastUtils
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.io.FileOutputStream
import java.lang.IllegalStateException


class BaseApplication : Application() {

    companion object {
        // 定义全局的Application
        lateinit var context: Application

        /** 是否客户端控制排序 */
        var eo = false
        /** 是否受限制 */
        var isLimited = false

        fun reset() {
            eo = false
            isLimited = false
        }
    }


    override fun onCreate() {
        super.onCreate()
        // 非App的线程不初始化其他的
        val processName = AppUtils.getMainProcessName(this)
        if (processName != packageName) return
        // 适配处理WebView
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && processName != null) {
            try {
                WebView.setDataDirectorySuffix(processName)
            } catch (e: IllegalStateException) {
                e.printStackTrace()
            }
        }
        context = this
        //设置LOG开关，默认为false
        LogC.init()
        // 设置loadingView
        LoadMoreModuleConfig.defLoadMoreView = LoadMoreView()
        // 初始化广告
        AdUtils.init(this, BuildConfig.DEBUG, true)
        // 初始化DLNA投屏相关
        ScreenCastUtils.init(this)

        RxUtils.doObservable ({
            // 每次启动都会删除阿里播放器的历史播放缓存
            val localCacheDir = File(context.externalCacheDir, "videoLocalCache")
            if (localCacheDir.exists()) {
                localCacheDir.deleteRecursively()
            }
            it.onNext(true)
        },{
            // 初始化播放器
            MixPlayerView.initPlayer(this, PlayerType.ALIYUN, isUseTX = false)
            if (BuildConfig.DEBUG) {
                // 阿里云日志设置
                Logger.getInstance(context).enableConsoleLog(false)
                Logger.getInstance(context).logLevel = Logger.LogLevel.AF_LOG_LEVEL_WARNING
            }
        })

        WBDownloadUtils.init(this) { tasks ->
            val event = DownloadInitEventNew(tasks)
            EventBus.getDefault().postSticky(event)
//            tasks.forEach {
//                Log.e("ExchangeManager", "当前任务 -> " + it.downloadTag)
//            }

            if (tasks.isEmpty()) return@init
            // 恢复下载
            WBDownloadUtils.resumeAllDownloads()
        }.setOnLoadCoverImageListener(object: OnLoadCoverImageListener {
            override fun onLoadCoverImageAsync(coverUrl: String, coverFile: File) {
                downloadCoverImageFile(coverUrl, coverFile)
            }
        })

    }


    private fun downloadCoverImageFile(coverUrl: String, coverFile: File){
        try {
            val request = ImageRequest.Builder(this@BaseApplication)
                .data(coverUrl)
                .build()
            val imageLoader = ImageLoader.Builder(this@BaseApplication)
                .build()
            val imageResult = imageLoader.executeBlocking(request)
            if (imageResult.drawable == null) {
                coverFile.delete()
                return
            }
            val bitmap = (imageResult.drawable as BitmapDrawable).bitmap
            if (coverFile.exists() && coverFile.length() > 0) {
                return
            }
            FileOutputStream(coverFile).use { outStream ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            coverFile.delete()
        }
    }

}